<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 后台订单控制器
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   allen.qiang
 */

quanli_require('module/base/goodsHandler.class.php');
quanli_require('module/base/billHandler.class.php');
quanli_require('module/base/customerHandler.class.php');
quanli_require('module/base/promotionHandler.class.php');

class pa_bill {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //订单列表
                    $this->searchBillList();
                    break;

                case 2: //查看订单详情
               		$this->searchBillDetail();
               		break;

                case 3: //修改订单
                    $this->alterBill();
                    break;

                case 4: //新增订单
                    $this->addBill();
                    break;

                case 5: //导出订单
                    $this->exportBill();
                    break;

                default:
                    $this->toError('参数错误');
                    break;

            }
        } else {

            $this->toError('参数错误');

        }

    }

    /**
     * 转跳到错误页
     * @param string $msg 错误信息
     */
    private function toError( $msg ) {

        global $G_PGLOB;

        $G_PGLOB->display_error_page( $msg );

    }

    /**
     * 导出订单
     */
    private function exportBill() {

        global $G_PGLOB;

        //检查phpexcel类
        quanli_include('framework/phpExecl/PHPExcel.php');
        quanli_include('framework/phpExecl/PHPExcel/Writer/Excel2007.php');

        //实例化资源位类
        $billHandler = new billHandler( $G_PGLOB->DBCA );

        //查询订单信息
        $bill_array = $billHandler->searchBillInfo( $_REQUEST );

        //实例excel类
        $objPHPExcel = new PHPExcel();

        /**
         * 设置excel的属性
         */
        //创建人
        $objPHPExcel->getProperties()->setCreator("$G_PGLOB->currentUserName");
        //最后修改人
        $objPHPExcel->getProperties()->setLastModifiedBy("$G_PGLOB->currentUserName");
        //标题
        $objPHPExcel->getProperties()->setTitle("订单列表");
        //题目
        $objPHPExcel->getProperties()->setSubject("订单列表");
        //描述
        $objPHPExcel->getProperties()->setDescription("订单列表");
        /**
         * 设置excel的属性
         */

        /**
         * sheet
         */
        //设置当前的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //设置sheet的name
        $objPHPExcel->getActiveSheet()->setTitle('订单');
        /**
         * sheet
         */


        /**
         * 设置标题
         */
        $objPHPExcel->getActiveSheet()->setCellValue('A1', '订单号');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '包裹号');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '网点');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '会员名');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '订单状态');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '认领状态');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '创建人');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '下单时间');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '支付方式');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '付款状态');
        $objPHPExcel->getActiveSheet()->setCellValue('K1', '订单金额');
        $objPHPExcel->getActiveSheet()->setCellValue('L1', '运费');
        $objPHPExcel->getActiveSheet()->setCellValue('M1', '立减金额');
        $objPHPExcel->getActiveSheet()->setCellValue('N1', '优惠券金额');
        $objPHPExcel->getActiveSheet()->setCellValue('O1', '应付金额');
        $objPHPExcel->getActiveSheet()->setCellValue('P1', '积分价格');
        $objPHPExcel->getActiveSheet()->setCellValue('Q1', '配送状态');
        /**
         * 设置标题
         */

        /**
         * 添加数据
         */
        if ($bill_array) {

            $i = 2;

            foreach($bill_array as &$bill) {

                $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $bill['bill_no'] . "\t");
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $bill['package_no']);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $bill['extend_9']);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $bill['custID']);
                $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $bill['bill_status_name']);
                $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $bill['extend_3'] == 1 ? '已认领' : '未认领');
                $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $bill['creator']);
                $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $bill['createTime']);
                $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $bill['payTypeName']);
                $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $bill['pay_status_name']);
                $objPHPExcel->getActiveSheet()->setCellValue('K' . $i, $bill['bill_totalPaid']);
                $objPHPExcel->getActiveSheet()->setCellValue('L' . $i, $bill['deliver_fee']);
                $objPHPExcel->getActiveSheet()->setCellValue('M' . $i, $bill['bill_subtract_money']);
                $objPHPExcel->getActiveSheet()->setCellValue('N' . $i, $bill['bill_coupon_money']);
                $objPHPExcel->getActiveSheet()->setCellValue('O' . $i, sprintf('%.2f', $bill['bill_totalPaid']+$bill['deliver_fee']-$bill['bill_subtract_money']-$bill['bill_coupon_money']-$bill['bill_card_money']));
                $objPHPExcel->getActiveSheet()->setCellValue('P' . $i, $bill['bill_pointsPrice']);
                $objPHPExcel->getActiveSheet()->setCellValue('Q' . $i, $bill['deliver_status_name']);

                $i++;

            }

        }
        /**
         * 添加数据
         */

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);

        //文件名称
        $fileName = '订单_' . date('YmdHis') . '.xlsx';

        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        header("Content-Type: application/force-download");
        header("Content-Disposition:inline;filename=$fileName");
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter->save('php://output');

    }

    /**
     * 新增订单
     */
    private function addBill() {

        global $G_PGLOB;

        if (!isset($_REQUEST['pcustID']) || !is_numeric($_REQUEST['pcustID'])) {
            $this->toError('参数错误');
        }

        //实例化会员类
        $customerHandler = new customerHandler( $G_PGLOB->DBCA );

        //查询会员信息
        $customer_array = $customerHandler->getCustomerInfo( $_REQUEST );
        if (!$customer_array) {
            $this->toError('会员信息没有找到');
        }

        //获得会员账户余额
        $result_array = $G_PGLOB->EAI->memberAccount( $_REQUEST['pcustID'], G_PAYTYPE_CASH, $G_PGLOB->DBCA );
        if ($result_array['code'] == 200) {
            $customer_array[0]['cashAmt'] = $result_array['data']['useableAccount'];
        } else {
            $customer_array[0]['cashAmt'] = 0;
        }

        //获得会员账户积分
        $result_array = $G_PGLOB->EAI->memberAccount( $_REQUEST['pcustID'], G_PAYTYPE_POINTS, $G_PGLOB->DBCA );
        if ($result_array['code'] == 200) {
            $customer_array[0]['pointsAmt'] = $result_array['data']['useableAccount'];
        } else {
            $customer_array[0]['pointsAmt'] = 0;
        }

        //查询会员最后一次购买记录
        $cust_buy_log_array = $customerHandler->searchCustBuyLog( $_REQUEST['pcustID'] );

        //实例化item类
        $itemHandler = new itemHandler( $G_PGLOB->DBCA );

        //查询发票内容选项
        $item_array = array(
            'itemCategoryID' => 4,
            'useFlg' => 1,
            'sortname' => 'itemID',
            'sortorder' => 'DESC'
        );
        $invoice_content_array = $itemHandler->searchItem( $item_array );

        //查询配送时间选项
        $item_array = array(
            'itemCategoryID' => 5,
            'useFlg' => 1,
            'sortname' => 'itemID',
            'sortorder' => 'DESC'
        );
        $send_time_array = $itemHandler->searchItem( $item_array );

        $G_PGLOB->smarty->assign_by_ref('customer_array', $customer_array[0]);
        $G_PGLOB->smarty->assign_by_ref('cust_buy_log_array', $cust_buy_log_array);
        $G_PGLOB->smarty->assign_by_ref('invoice_content_array', $invoice_content_array);
        $G_PGLOB->smarty->assign_by_ref('send_time_array', $send_time_array);


        $bill_array = array(

            'bill_no' => null,

            'bill_status' => 0,

            'change_time' => time(),

            'message' => null,

            'goods' => array(
                'general' => array()
            ),

            'master' => array()

        );
        $G_PGLOB->sessionCache_set('back_cart_' . $_REQUEST['pcustID'], $bill_array, 0, true);

        $G_PGLOB->smarty->display('bill/billAdd.tpl');

    }

    /**
     * 订单修改
     */
    private function alterBill() {

        global $G_PGLOB;

        if (!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no']))
            $G_PGLOB->display_error_page('缺少参数');

        //实例化订单类
        $billHandler = new billHandler( $G_PGLOB->DBCA );

        //实例化商品类
        $goodsHandler = new goodsHandler( $G_PGLOB->DBCA );

        $arg_array = array(
            'bill_no' => $_REQUEST['bill_no']
        );

        //查询订单主表信息
        $bill_master_array = $billHandler->searchBillInfo( $arg_array );
        if (!$bill_master_array)
            $G_PGLOB->display_error_page(sprintf('订单号：%s，订单信息没有找到', $_REQUEST['bill_no']));
        $bill_master_array = $bill_master_array[0];

        if ($bill_master_array['bill_status'] == 4)
            $G_PGLOB->display_error_page(sprintf('订单号：%s，订单已配送，无法修改', $_REQUEST['bill_no']));

        if ($bill_master_array['bill_status'] == 5)
            $G_PGLOB->display_error_page(sprintf('订单号：%s，订单已取消，无法修改', $_REQUEST['bill_no']));

        //查询订单商品信息
        $bill_goods_array = $billHandler->searchBillGoods( $arg_array );

        //查询订单支付信息
        $bill_pay_array = $billHandler->searchBillPay( $arg_array );

        //查询内部留言
        $arg_array = array(
            'bill_no' => $_REQUEST['bill_no'],
            'sortname' => 'createTime',
            'sortorder' => 'asc'
        );
        $bill_remark_array = $billHandler->searchBillRemark( $arg_array );


        //实例化item类
        $itemHandler = new itemHandler( $G_PGLOB->DBCA );

        //查询发票内容选项
        $item_array = array(
            'itemCategoryID' => 4,
            'useFlg' => 1,
            'sortname' => 'itemID',
            'sortorder' => 'DESC'
        );
        $invoice_content_array = $itemHandler->searchItem( $item_array );


        //查询配送时间选项
        $item_array = array(
            'itemCategoryID' => 5,
            'useFlg' => 1,
            'sortname' => 'itemID',
            'sortorder' => 'DESC'
        );
        $send_time_array = $itemHandler->searchItem( $item_array );


        //实例化会员类
        $customerHandler = new customerHandler( $G_PGLOB->DBCA );

        //查询会员信息
        $arg_array = array(
            'pcustID' => $bill_master_array['pcustID']
        );
        $customer_array = $customerHandler->getCustomerInfo( $arg_array );
        if (!$customer_array)
            $G_PGLOB->display_error_page('会员信息没有找到');

        //获得会员等级信息
        $cust_rank = $customerHandler->getCustRand( $bill_master_array['pcustID'] );

        //更新商品价格
        foreach($bill_goods_array as &$goods) {

            if ($goods['goods_from'] == 1) {

                $arg_array = array(
                    'postID' => $goods['postID']
                );
                $goods_detail_array = $goodsHandler->searchGoodsSale( $arg_array );

                //计算商品实售价格及查询促销活动
                $goodsHandler->shopCalculationGoodsPrice($cust_rank, $goods_detail_array);

                $goods['price'] = $goods_detail_array['price'];
                $goods['addPoints'] = 0;
                $goods['salePoints'] = $goods_detail_array['salePoints'];
                $goods['marketPrice'] = $goods_detail_array['marketPrice'];
                $goods['salePrice'] = $goods_detail_array['salePrice'];
                $goods['goodsWeight'] = $goods_detail_array['goodsWeight'];
                $goods['promotion'] = $goods_detail_array['promotion'];
                $goods['img_link'] = $goods_detail_array['img_link'];
                $goods['link'] = $goods_detail_array['link'];
                $goods['product_code'] = $goods_detail_array['product_code'];


            }

        }

        $G_PGLOB->smarty->assign_by_ref('bill_master_array', $bill_master_array);
        $G_PGLOB->smarty->assign_by_ref('bill_goods_array', $bill_goods_array);
        $G_PGLOB->smarty->assign_by_ref('bill_pay_array', $bill_pay_array);
        $G_PGLOB->smarty->assign_by_ref('bill_trace_array', $bill_trace_array);
        $G_PGLOB->smarty->assign_by_ref('bill_remark_array', $bill_remark_array);
        $G_PGLOB->smarty->assign_by_ref('invoice_content_array', $invoice_content_array);
        $G_PGLOB->smarty->assign_by_ref('send_time_array', $send_time_array);
        $G_PGLOB->smarty->assign_by_ref('customer_array', $customer_array[0]);
        $G_PGLOB->smarty->assign_by_ref('cust_rank', $cust_rank);

        $bill_array = array(

            'bill_no' => null,

            'bill_status' => 0,

            'change_time' => time(),

            'message' => null,

            'goods' => array(
                'general' => array()
            ),

            'master' => array()

        );
        $G_PGLOB->sessionCache_set('cart_backend_' . $bill_master_array['pcustID'], $bill_array, 0, true);

        $G_PGLOB->smarty->display('bill/billAlter.tpl');

    }


    /**
     * 订单列表
     */
    private function searchBillList() {

        global $G_PGLOB;

        $G_PGLOB->smarty->display('bill/billSearch.tpl');
    }

    /**
     * 查看订单详情
     */
    private function searchBillDetail() {
    	global $G_PGLOB;

    	//实例化订单类
    	$billHandler = new billHandler( $G_PGLOB->DBCA );

    	$arg_array = array(
    		'bill_no' => $_REQUEST['bill_no']
    	);

    	$bill_info = $billHandler->searchBillInfo( $arg_array );

    	if (!empty($bill_info)) {
    		$bill_info = $bill_info[0];
    	}

    	//查找订单商品
    	$arg_goods_array = array( 'bill_no' => $_REQUEST['bill_no'] );
    	$bill_goods = $billHandler->searchBillGoods( $arg_goods_array );

		//查找订单支付
		$arg_bill_pay = array( 'bill_no' => $_REQUEST['bill_no']);
		$bill_pay = $billHandler->searchBillPay( $arg_bill_pay );

		//订单轨迹
		$arg_bill_trace = array( 'bill_no' => $_REQUEST['bill_no']);
		$bill_trace = $billHandler->searchBillTrace( $arg_bill_trace );

		//内部留言
		$arg_inner_word = array(
			'bill_no' => $_REQUEST['bill_no'],
			'sortname' => 'createTime',
			'sortorder' => 'asc'
			);
		$bill_remark = $billHandler->searchBillRemark( $arg_inner_word );

    	$G_PGLOB->smarty->assign_by_ref('bill_goods', $bill_goods);
    	$G_PGLOB->smarty->assign_by_ref('bill_remark', $bill_remark);
    	$G_PGLOB->smarty->assign_by_ref('bill_trace', $bill_trace);
    	$G_PGLOB->smarty->assign_by_ref('bill_pay', $bill_pay);
    	$G_PGLOB->smarty->assign_by_ref('bill_info', $bill_info);

        $G_PGLOB->smarty->display('bill/billDetail.tpl');

    }

}